package com.spring.team_propaganda_system.controller;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spring.team_propaganda_system.dao.ArticleDao;
import com.spring.team_propaganda_system.dao.ClassificationDao;
import com.spring.team_propaganda_system.entity.Article;
import com.spring.team_propaganda_system.entity.Classification;
import com.spring.team_propaganda_system.entity.User;
import com.spring.team_propaganda_system.utils.JwtToken;
import com.spring.team_propaganda_system.utils.MyUtil;
import com.spring.team_propaganda_system.utils.RedisUtil;
import com.spring.team_propaganda_system.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@CrossOrigin
@Controller
@RequestMapping("/classification")
@Api(value = "ClassificationController", description = "分类相关api")
@Transactional
public class ClassificationController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required = false)
    private ClassificationDao classificationDao;
    @Autowired(required = false)
    private ArticleDao articleDao;
    @Autowired(required = false)
    private RedisUtil redisUtil;

    /**
     * 添加分类
     * @param classification_name
     * @param user_name
     * @param Authorization
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */
    @ApiOperation("添加分类")
    @PostMapping("/web/addClassification")
    @ResponseBody
    public ResponseEntity addClassification(@RequestParam(required = true) String classification_name,
                                            @RequestParam(required = true) String user_name,
                                            @RequestHeader String Authorization) throws IOException, TokenExpiredException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User user = JwtToken.unsign(token, User.class);
        //用户角色，分微信用户和老师用户，1代表微信用户，2代表老师用户,默认为微信用户
        if (user.getUser_role()!=2){
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        //根据user_jobNumber查询数据库是否有该用户存在，不存在则注册，存在则注册失败
        QueryWrapper<Classification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classification_name", classification_name);
        Classification classification = classificationDao.selectOne(queryWrapper);
        //User userFromBase = userDao.selectById(user_name);
        if (classification == null){
            responseEntity = ResponseEntity.ok();
            Classification classification1 = new Classification();
            classification1.setClassification_name(classification_name);
            classification1.setUser_name(user_name);
            classificationDao.insert(classification1);
            responseEntity.putDataValue("classification_id",classification1.getClassification_id());
            responseEntity.putDataValue("msg","分类添加成功");
        }else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","分类添加失败");
        }
        return responseEntity;
    }

    /**
     * 修改分类信息
     * @param classification_id
     * @param classification_name
     * @param user_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("修改分类信息")
    @PutMapping("/web/updateClassification")
    @Transactional
    @ResponseBody
    public ResponseEntity updateClassification(@RequestParam(required = true) int classification_id,
                                        @RequestParam(required = false) String classification_name,
                                        @RequestParam(required = false) String user_name,
                                        @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else if (users.getUser_role()!=2) {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "没有权限");
            return responseEntity;

        } else {
            responseEntity = ResponseEntity.ok();
            Classification classification = classificationDao.selectById(classification_id);

            String classification_name1 = classification.getClassification_name();
            QueryWrapper<Classification> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("classification_name", classification_name);
            List<Classification> list1 = classificationDao.selectList(queryWrapper1);
            System.out.println("列表为:"+list1);
            if (list1.size()>0) {
                responseEntity = ResponseEntity.unauthorized();
                responseEntity.putDataValue("msg", "分类名已存在,请换一个分类名");
                return responseEntity;
            } else {
                QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("classification_name", classification_name1);
                List<Article> list = articleDao.selectList(queryWrapper);

                classification.setClassification_name(classification_name);
                classification.setUser_name(user_name);
                classificationDao.updateById(classification);
                for (Article article : list) {
                    article.setClassification_name(classification_name);
                    articleDao.updateById(article);
                }
                responseEntity.putDataValue("msg", "分类修改成功");
                //删除缓存
                String key = "classification_" + classification_id;
                if (redisUtil.hasKey(key)) {
                    redisUtil.del(key);
                }
                return responseEntity;
            }
        }
    }

    /**
     * 根据classification_id查询分类信息
     * @param classification_id
     * @return
     * @throws IOException
     */
    @ApiOperation("根据classification_id查询分类信息")
    @PutMapping("/web/selectByClassificationId")
    @ResponseBody
    public ResponseEntity selectByClassificationId(@RequestParam(required = true) Integer classification_id) throws IOException {
        ResponseEntity responseEntity;
        int is_delete = 0;
        //查询缓存
        String key="classification_"+classification_id;
        boolean b = redisUtil.hasKey(key);
       //如果redis中存在 查询缓存
        if (b){
            Classification o = (Classification)redisUtil.get(key);
            responseEntity=ResponseEntity.ok();
            responseEntity.putDataValue("classification",o);
            return responseEntity;
        }
        QueryWrapper<Classification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", is_delete);
        queryWrapper.eq("classification_id", classification_id);
        Classification classification=classificationDao.selectOne(queryWrapper);
        responseEntity=ResponseEntity.ok();
        //设置缓存
        redisUtil.set("classification_"+classification_id,classification);
        responseEntity.putDataValue("classification",classification);
        return responseEntity;

    }

    /**
     * 根据id删除分类信息
     * @param classification_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @Transactional
    @ApiOperation("根据id删除分类信息")
    @PutMapping("/web/deleteClassification")
    @ResponseBody
    public ResponseEntity deleteClassification(@RequestParam(required = true) Integer classification_id,
                                               @RequestHeader String Authorization)throws IOException{
        ResponseEntity responseEntity;
        String token=Authorization;
        if(flag=myUtil.judgeToken(token)){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User users=JwtToken.unsign(token,User.class);
        if(users==null){
            responseEntity=ResponseEntity.notFound();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        } else if (classification_id==1) {
            responseEntity=ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg","这是主分类，不可删除");
            return responseEntity;
        } else if (users.getUser_role() == 2) {
            Classification classification = classificationDao.selectById(classification_id);
            if (classification != null) {

                String classification_name = classification.getClassification_name();
                QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("classification_name", classification_name);
                List<Article> article = articleDao.selectList(queryWrapper);
                String classification_name2 = "未分类";
                for (Article article1 : article) {
                    article1.setClassification_name(classification_name2);
                    articleDao.updateById(article1);
                }
                QueryWrapper<Classification> queryWrapper1 = new QueryWrapper<>();
                classificationDao.delete(queryWrapper1);
                //删除缓存
                String key = "classification_" + classification_id;
                if (redisUtil.hasKey(key)){
                    redisUtil.del(key);
                }
                responseEntity = ResponseEntity.ok();
                responseEntity.putDataValue("msg", "删除成功");
                return responseEntity;
            }
        }
        responseEntity=ResponseEntity.unauthorized();
        responseEntity.putDataValue("msg","没有权限");
        return responseEntity;
    }
    /**
     * 分类列表
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("分类列表")
    @PostMapping("/web/ClassificationList")
    @ResponseBody
    public ResponseEntity ClassificationList(
                                       HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        QueryWrapper<Classification> wrapper = new QueryWrapper<>();
//        int is_delete=0;
//        wrapper.eq("is_delete", is_delete);
        List<Classification> list = classificationDao.selectList(wrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("classification",list);
        responseData.putDataValue("msg","成功");
        return responseData;
    }
    /**
     * 统计分类数量
     */
    @ApiOperation("统计分类数量")
    @GetMapping("/web/count")
    @ResponseBody
    public ResponseEntity count() throws IOException {
        ResponseEntity responseData;
        QueryWrapper<Classification> queryWrapper = new QueryWrapper<>();
        int  count =classificationDao.selectCount(queryWrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("count", count);
        return responseData;
    }

}
